.PHONY: all clean

MAKE_DIR := $(realpath .)
BULID_DATE := $(shell date +"%Y-%m-%d %H:%M:%S")

SRC_DIR := src
LIB_DIR := lib
INC_DIR := inc

SRC_TYPE := .cpp
ASM_TYPE := .s
INC_TYPE := .h
OBJ_TYPE := .o
LIB_TYPE := .a
DEP_TYPE := .d

BUILD_DIR := build
OBJS_DIR   := $(BUILD_DIR)/objs
DEPS_DIR   := $(BUILD_DIR)/deps
BIN_DIR    := $(BUILD_DIR)/bin

DIRS := $(BUILD_DIR) $(OBJS_DIR) $(DEPS_DIR) $(BIN_DIR)

TARGET_NAME := demolib
TARGET := $(BIN_DIR)/$(TARGET_NAME)

SRCS := $(wildcard $(SRC_DIR)/*$(SRC_TYPE))  
SRCS := $(notdir $(SRCS))

OBJS := $(SRCS:$(SRC_TYPE)=$(OBJ_TYPE))
OBJS := $(addprefix $(OBJS_DIR)/, $(OBJS))

DEPS := $(SRCS:$(SRC_TYPE)=$(DEP_TYPE))
DEPS := $(addprefix $(DEPS_DIR)/, $(DEPS))

CC := gcc
CXX := g++
OBJDUMP := objdump
CFLAGS := -Wall -I $(INC_DIR) -std=c++17 -m32 -lpthread
LFLAGS := 

ifeq ("$(DEBUG)", "true")
DFLAGS := -g
else
DFLAGS :=
endif

MKDIR := mkdir -p
RM := rm -rf

vpath %$(SRC_TYPE) $(SRC_DIR)
vpath %$(INC_TYPE) $(INC_DIR)

all : $(TARGET) 
	@echo "Successfully build the project : $^ ..."
	$(organization_info)

ifeq ("$(MAKECMDGOALS)", "all")
-include $(DEPS)
endif

ifeq ("$(MAKECMDGOALS)", "")
-include $(DEPS)
endif

$(TARGET) : $(DEPS) $(DIRS) $(OBJS)
	$(CXX) -o $@ $(filter %$(OBJ_TYPE), $^) $(LIBS) $(LFLAGS) $(CFLAGS) ${DFLAGS}
	$(OBJDUMP) -D $@ > $(TARGET)$(ASM_TYPE)


$(DIRS) : 
	$(MKDIR) $@

$(OBJS_DIR)/%$(OBJ_TYPE) : %$(SRC_TYPE)
	$(CXX) -c $< -o $@ $(CFLAGS) $(DFLAGS)

#自动生成依赖关系
ifeq ("$(wildcard  $(DEPS_DIR))", "")
$(DEPS_DIR)/%$(DEP_TYPE) : $(DEPS_DIR) %$(SRC_TYPE)
else
$(DEPS_DIR)/%$(DEP_TYPE) : %$(SRC_TYPE)
endif
	@echo "build $@"
	@set -e;\
	$(CXX) -MM -E $(filter %$(SRC_TYPE), $^) $(CFLAGS) | sed 's,\(.*\)\$(OBJ_TYPE)[ :]*,$(DEPS_DIR)/\1$(OBJ_TYPE) $@ : ,g' > $@

rebuild :
	@$(MAKE) clean
	@$(MAKE) all

clean :
	$(RM) $(BUILD_DIR)

#打印组织、作者、项目目录、构建时间等信息
override define organization_info
	@echo "--------------------------------------------------------"
	@echo "Company : houyannian"
	@echo "Author : houyannian"
	@echo "make directory : $(MAKE_DIR)"
	@echo "build directory: $(BUILD_DIR)"
	@echo "build date : $(BULID_DATE)"
	@echo "--------------------------------------------------------"
endef